package com.tianji.learning.mq;

import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.mq.message.LearningRecordMessage;
import com.tianji.learning.service.impl.LearningRecordServiceImpl2;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Covey
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LearningRecordListener {

    private final LearningRecordServiceImpl2 learningRecordService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.record.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.LEARNING_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.LEARNING_RECORD_KEY
    ))
    public void listenLearningRecord(LearningRecordMessage message) throws IOException {
        try {
            // 手动设置用户上下文
            UserContext.setUser(message.getUserId());
            learningRecordService.handleVideoRecordAsync(message.getRecordDTO());
        } catch (Exception e) {
            log.error("处理学习记录消息失败，进行重试: {}", e.getMessage());
        } finally {
            // 清理用户上下文
            UserContext.removeUser();
        }
    }
}